package com.oschina.bottle.mysql.factory;

import com.oschina.bottle.mysql.DataSourceProperties;
import com.oschina.bottle.mysql.utils.DBHelper;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.Ordered;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2016/11/19
 * @since 1.0
 */
@Configuration
@SuppressWarnings("SpringJavaAutowiringInspection")
@EnableTransactionManagement(order = Ordered.LOWEST_PRECEDENCE - 1)
@EnableConfigurationProperties(DataSourceProperties.class)
//@MapperScan("com.oschina")
public class DBAutoConfiguration
{
    @Autowired
    private DataSourceProperties dbProperties;

    public SqlSessionTemplate getSqlSession()
        throws Exception
    {
        return new SqlSessionTemplate(sqlSessionFactoryBean().getObject());
    }

    @Bean
    @Scope("prototype") SqlSessionTemplate sqlSessionTemplate()
        throws Exception
    {
        return this.getSqlSession();
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource());
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        /** 添加mapper 扫描路径 */
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "**/mapper/*Mapper.xml";
        sqlSessionFactory.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        return sqlSessionFactory;
    }

    @Bean
    DataSource dataSource() {
        return DBHelper.buildDataSource(dbProperties);
    }

    @Bean
    DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage(dbProperties.getMapperPackage());
        return configurer;
    }
}
